<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
require_once '../../model/users.php';
include_once("../../model/trade.php");
include_once("../../model/state.php");
include_once("../../model/budget.php");
include_once '../../model/email.php';
require_once '../../redirect.php';

if($_SESSION['getbids_id']=='')
{	
	@header("location:".SITE_URL."/signin/");
	exit;
}
if($_SESSION['user_type'] == '4')
{
	@header("location:".SITE_URL."/leads/");
	exit;
}

## creating objects of required models
$userObj 		= new Model_Users();
$tradeObj = new Model_TRADE();
$emailObj 	= new  Model_Email();
$stateObj = new Model_State();
$budgetObj = new Model_Budget();

/*===========================================================================*/
$userId =$_SESSION['getbids_id'];
if($userId!='')
{
	$userDetArray = $userObj->getUserDetailsByUserId($userId);
	$smarty->assign("userDetArray", $userDetArray);	
}
/*===========================================================================*/	


if($_GET['companyname'] !='')
{
	$companyname=str_replace("_"," ",$_GET['companyname']);
	$userdetail = $userObj->getUserDetailsByCompanyName($companyname);
	$userid = $userdetail['id'];	
	$getuserdetail = $userObj->getUserDetailsByUserId($userid);
	
	if($getuserdetail['tradeid']!='')
	{
		$exp_arr_trade = @explode(",",$getuserdetail['tradeid']);
		for($e=0;$e<count($exp_arr_trade);$e++)
		{
			$new_arr_trade[] = "'".$exp_arr_trade[$e]."'";	
		}	
		if($new_arr_trade[0]!='')
		{
			$imp_str_trade = 	@implode(",",$new_arr_trade);
		}
		else
			$imp_str_trade = '0';
				
		$getTradecat = $tradeObj->new_getTradeCategoryDetailsById($imp_str_trade);	
		$getuserdetail['trade_name'] = $getTradecat['trade_category'];
	}
	
	if($getuserdetail['workarea']!='')
	{
		$getpostaldetail = $stateObj->getPostalCodeDetailsByPostalId($getuserdetail['workarea']);
		$getuserdetail['suburbname'] = $getpostaldetail['suburb'];
	}
	
	if($getpostaldetail['state']!='')
	{
		$getstatedetail = $stateObj->getStateDetailsByISOCODE($getpostaldetail['state']);
		$getuserdetail['statename'] = $getstatedetail['state_name'];
		$getuserdetail['stateid'] = $getstatedetail['state_id'];
		
		$getallpostalcode = $stateObj->getAllSuburb($getpostaldetail['state']);
					
			for($i=0;$i<count($getallpostalcode);$i++)
			{
				$getallpostalcode_arr[] ="'".$getallpostalcode[$i]["postcode"]."'";
			}
			if($getallpostalcode_arr[0]!='')
				$implodearray = @implode(",",$getallpostalcode_arr);
			else
				$implodearray = 0;	
				
			$postalcode = $implodearray; 
	}
	
	$userreviewcount=$userObj->getUserRatingCount($getuserdetail['id']);	
	$getuserdetail['userreviewcount'] =$userreviewcount['cnt']	;
			
	$userAllleadcount = $userObj->getleadcountofTradesmanByUserId($getuserdetail['id']);	
	if($userAllleadcount['cnt']!='0' && $userreviewcount['cnt']	!='0')
	{
			$positive =( $userreviewcount['cnt']/$userAllleadcount['cnt'] ) *100;
			$getuserdetail['positive'] =  number_format($positive,2);
	}
	else
		$getuserdetail['positive'] = 0;
		
	
	$userlastreviewdetail=$userObj->getUserLastReviewDetail($getuserdetail['id']);	
	if($userlastreviewdetail['job_id']!='')
	{
		$getjobdetail=$userObj->getJobDetailsById($userlastreviewdetail['job_id']);	
		$getuserdetail['userlastreview_trade_category'] = $getjobdetail['trade_category'];
		$getuserdetail['userlastreview_job_desc'] = $getjobdetail['job_desc'];
	}			
	$getuserdetail['userlastreview_feedback'] =$userlastreviewdetail['message'];
	$getuserdetail['userlastreview_username'] =$userlastreviewdetail['first_name']." ".$userlastreviewdetail['last_name'];
	$getuserdetail['userlastreview_added_date'] =$userlastreviewdetail['added_date'];
	if($userlastreviewdetail['added_date']!='')
	{
		$timestamp = strtotime($userlastreviewdetail['added_date']);
	
		$getuserdetail['userlastreview_added_date_suffix'] = date('S', $timestamp);
	}
	

	$userreviewdetail=$userObj->getUserAllReviewDetail($getuserdetail['id']);	
	for($i=0;$i<count($userreviewdetail);$i++)
	{
		if($userreviewdetail[$i]['job_id']!='')
		{
			$getjobdetail=$userObj->getJobDetailsById($userreviewdetail[$i]['job_id']);	
			$userreviewdetail[$i]['userlastreview_trade_category'] = $getjobdetail['trade_category'];
			$userreviewdetail[$i]['userlastreview_job_desc'] = $getjobdetail['job_desc'];
		}			
		if($userreviewdetail[$i]['added_date']!='')
		{
			$timestamp = strtotime($userreviewdetail[$i]['added_date']);
		
			$userreviewdetail[$i]['userlastreview_added_date_suffix'] = date('S', $timestamp);
		}
	}
	$smarty->assign('userreviewdetail', $userreviewdetail);	

	
	if($getuserdetail['id']!='')
	{
		$userworkphotodetail=$userObj->getAllWorkPhotoByUserID($getuserdetail['id']);	
		//echo "<pre>";print_R($userworkphotodetail);die();
		$smarty->assign('userworkphotodetail', $userworkphotodetail);		
	}
	
	$topTradesjobs= $userObj->gettopthreeTradesjobs();	
	$smarty->assign('topTradesjobs', $topTradesjobs);
	
	$relatedTradesjobs= $userObj->getrelatedTradesjobs($postalcode);	
	$smarty->assign('relatedTradesjobs', $relatedTradesjobs);
	
	$smarty->assign('user_details', $getuserdetail);
}
//echo "<pre>";print_R($_POST);die();

if($_POST['trade']!='' && $_POST['jobtype']!='' && $_POST['emailaddress']!='')
{
	//echo "<pre>";print_R($_POST);die();
	
	$getuserdetail = $userObj->chkUserNameExist($_POST['emailaddress']);
	
	
	if($getuserdetail['user_type'] == 3 || $getuserdetail['id']=='')	
	{
		
		$gettradedetail = $tradeObj->getTradeCategoryDetailsById($_POST['trade']);
		$getjobdetail = $tradeObj->getTradeCategoryDetailsById($_POST['jobtype']);
		$budgetdetail = $budgetObj->getBudgetDetailsById($_POST['approx_budget']);
			if($getuserdetail['email'] == $_POST['emailaddress'])
			{
				
				// add user post job if user exits
				$userPostArray = array();
				$userPostArray["trade_id"] 			= $_POST['trade'];
				$userPostArray["jobtype_id"]		= $_POST['jobtype'];					
				$userPostArray["job_desc"] 			= $_POST['describe_job'];
				$userPostArray['workstart'] 		= $_POST['work_to_start'];	
				$userPostArray['approx_budget']		= $_POST['approx_budget'];						
				$userPostArray['area'] 				= $_POST['postcode'];
				$userPostArray['user_id'] 			= $getuserdetail['id'];			
				$userPostArray["date_added"] 		= getCurDate();
				$userPostArray["status"] 			= 1;
				$jobID = $userObj->addUserPostJobByValue($userPostArray);
				
				//$password = getRandomNumber();
				$userDetArray = array();
				$userDetArray["first_name"] 	= $_POST['fname'];
				$userDetArray["last_name"]		= $_POST['lname'];					
				$userDetArray['phone_number'] 	= $_POST['mobno'];
				//$userDetArray['password'] 		= md5($password);	
				$userObj->editUserValueById($userDetArray,$getuserdetail['id']);
				
				
					// send email message
					$email_message = $emailObj->getEmailById(21);
					$e_subject = $email_message['email_subject'];
					$message = $email_message['email_content']; 
					
					$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
					
					$message = str_replace('[NAME]', trim($_POST['fname'])." ".trim($_POST['lname']) , $message);
					$message = str_replace('[SITENAME]', SITENAME, $message);
					$message = str_replace('[USERNAME]', trim($_POST['emailaddress']), $message);
					$message = str_replace('[PHONENUMBER]',trim($_POST['mobno']), $message);
					$message = str_replace('[EMAIL]',trim($_POST['emailaddress']), $message);
					
					$message = str_replace('[DATEADDED]',trim($userPostArray["date_added"]), $message);
					$message = str_replace('[JOBSKILL]',trim($getjobdetail['trade_category']), $message);
					$message = str_replace('[DESCRIPTION]',trim($_POST['describe_job']), $message);
					$message = str_replace('[BUDGET]',"$".trim($budgetdetail['budget_name']), $message);
					$message = str_replace('[POSTCODE]',trim($_POST['postcode']), $message);
					
					$message = str_replace('[SITE_LINK]', SITE_URL, $message);
					
					$to= trim($_POST['emailaddress']); 
					$adminEmail = $adminObj->getAdminDetails();
					$from = $adminEmail;
					$fromname= SITENAME;
									 
					$emailTemplate = file_get_contents('../../emailtemplate.html');
					$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
					$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
					$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
					//echo $template_msg; exit;
					if(trim($to) != '')
					@send_mail($to, $template_msg, $subject, $from, $fromname); 
					
					
					// code for add user job view table
					$userJobViewArray["userid"] 	= $userid;					
					$userJobViewArray["jobid"] 		= $jobID;
					$userJobViewArray["message"] 		= "Request a qoute";//stripslashes($_POST['message']);
					$userJobViewArray["date_added"] = date('Y-m-d');
					$jobviewId = $userObj->addUserViewJOBByValue($userJobViewArray);
					
					
					//get user job view detail
					$getuserjobviewdetail = $userObj->getUserViewjobDetailsByID($jobviewId);
					
					
					//tradesman detail 
					$TradesmanuserDetArray = $userObj->getUserDetailsByUserId($getuserjobviewdetail['userid']);
				
					$userjobviewArray = array();
					$userjobviewArray['status']	= 'Accept';
					$userObj->editUserViewJobValueById($userjobviewArray,$jobviewId);	
					
					$userjobArray = array();
					$userjobArray['project_status']	= 'Accept';
					$userObj->editJobPostValueByJOBId($userjobArray,$jobID);
					
					
					// send email message to Tradesman accepted
					$email_message = $emailObj->getEmailById(13);
					$e_subject = $email_message['email_subject'];
					$message = $email_message['email_content']; 
					
					$subject = str_replace('[STATUS]', 'Accepted', $e_subject);
					$subject = str_replace('[SITENAME]', SITENAME, $subject);		 
				
					$message = str_replace('[TRADESMAN_NAME]', trim($TradesmanuserDetArray["first_name"])." ".trim($TradesmanuserDetArray["last_name"]) , $message);	
					$message = str_replace('[HOME_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
					$message = str_replace('[STATUS]','Accepted', $message);
					$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
					$message = str_replace('[JOBTYPE]', trim($getjobdetail["trade_category"]), $message); 
					$message = str_replace('[JOBDESC]', trim($_POST["describe_job"]), $message); 
					$message = str_replace('[SITENAME]', SITENAME, $message);
					
					
					
					$to= trim($TradesmanuserDetArray["email"]);
					$adminEmail = $adminObj->getAdminDetails();
					$from = $adminEmail;
					$fromname= SITENAME;
									 
					$emailTemplate = file_get_contents('../../emailtemplate.html');
					$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
					$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
					$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
					//echo $template_msg; exit;
					if(trim($to) != '')
					@send_mail($to, $template_msg, $subject, $from, $fromname); 
					
				
				 $_SESSION['getbids_id']  = $getuserdetail['id'];			 
				 if($_GET['fname']=='' || $_GET['lname'] =='')
				 {
					$_SESSION['first_name']      = $getuserdetail['first_name'];
					$_SESSION['last_name']       = $getuserdetail['last_name'];
				 }
				 else
				 {
					$_SESSION['first_name']      = $_GET['fname'];
					$_SESSION['last_name']       = $_GET['lname'];	 
				 }
				 $_SESSION['user_type']       = $getuserdetail['user_type'];
				 $_SESSION['email']           = $getuserdetail['email'];
				
				$_SESSION['msg'] = "<div class='success_msg'><span>Your request a quote has been sent successfully !.</span></div>";
				header('location:'.SITE_URL.'/findtradesman/'.$_GET['companyname']);
				exit;
				
			}
			else
			{
					// add user if not exits
					$password = getRandomNumber();
					
					$userDetArray = array();
					$userDetArray["first_name"] 	= $_POST['fname'];
					$userDetArray["last_name"]		= $_POST['lname'];					
					$userDetArray["email"] 			= $_POST['emailaddress'];
					$userDetArray['username'] 		= $_POST['emailaddress'];
					$userDetArray['password'] 		= md5($password);
					$userDetArray['phone_number'] 	= $_POST['mobno'];					
					$userDetArray['postalcode'] 	= $_POST['postcode'];
					$userDetArray['user_type'] 		= 3;		
					$userDetArray["registered_date"] = getCurDate();
					$userDetArray["user_status"] 	= 0;
					$userId = $userObj->addUserByValue($userDetArray);
					
					// add user post job if user not exits
					$userPostArray = array();
					$userPostArray["trade_id"] 			= $_POST['trade'];
					$userPostArray["jobtype_id"]		= $_POST['jobtype'];					
					$userPostArray["job_desc"] 			= $_POST['describe_job'];
					$userPostArray['workstart'] 		= $_POST['work_to_start'];	
					$userPostArray['approx_budget']		= $_POST['approx_budget'];						
					$userPostArray['area'] 				= $_POST['postcode'];
					$userPostArray['user_id'] 			= $userId;			
					$userPostArray["date_added"] 		= getCurDate();
					$userPostArray["status"] 			= 0;
					$JobID = $userObj->addUserPostJobByValue($userPostArray);
					
					
					// send email message
					$email_message = $emailObj->getEmailById(20);
					$e_subject = $email_message['email_subject'];
					$message = $email_message['email_content']; 
					
					$subject = str_replace('[SITENAME]', SITENAME, $e_subject);	
					
					$activationLink = SITE_URL."/signin/".md5($userId)."/".base64_encode($JobID)."/".base64_encode($userid)."/activation/";		 
					$activationLink = '<a href="'.$activationLink.'">'.$activationLink.'</a>';		 
					
					$message = str_replace('[NAME]', trim($_POST['fname'])." ".trim($_POST['lname']) , $message);
					$message = str_replace('[SITENAME]', SITENAME, $message);
					$message = str_replace('[USERNAME]', trim($_POST['emailaddress']), $message);
					$message = str_replace('[PASSWORD]', trim($password), $message); 
					$message = str_replace('[PHONENUMBER]',trim($_POST['mobno']), $message);
					$message = str_replace('[EMAIL]',trim($_POST['emailaddress']), $message);
					
					$message = str_replace('[DATEADDED]',trim($userPostArray["date_added"]), $message);
					$message = str_replace('[JOBSKILL]',trim($getjobdetail['trade_category']), $message);
					$message = str_replace('[DESCRIPTION]',trim($_POST['describe_job']), $message);
					$message = str_replace('[BUDGET]',"$".trim($budgetdetail['budget_name']), $message);
					$message = str_replace('[POSTCODE]',trim($_POST['postcode']), $message);
					
					$message = str_replace('[ACTIVATIONURL]', $activationLink, $message);
					
					$message = str_replace('[SITE_LINK]', SITENAME, $message);
					
					$to= trim($_POST['emailaddress']); 
					$adminEmail = $adminObj->getAdminDetails();
					$from = $adminEmail;
					$fromname= SITENAME;
									 
					$emailTemplate = file_get_contents('../../emailtemplate.html');
					$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
					$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
					$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
					//echo $template_msg; exit;
					if(trim($to) != '')
					@send_mail($to, $template_msg, $subject, $from, $fromname); 
					
					/* $_SESSION['getbids_id']  = $userId;			 
					 $_SESSION['first_name']      = $_GET['fname'];
					 $_SESSION['last_name']       = $_GET['lname'];	 				 
					 $_SESSION['user_type']       = 3;
					 $_SESSION['email']           = $_GET['emailaddress'];
					//$_SESSION['msg'] = "<div class='success_msg'><span>You have sucessfully post job!</span></div>";
					//redirect_to_link(SITE_URL.'/register/registersuccess/');*/
					
					$_SESSION['msg'] = "<div class='success_msg'><span>Your request a quote has been sent successfully! Please check your mail for further details.</span></div>";
					header('location:'.SITE_URL.'/findtradesman/'.$_GET['companyname']);
					exit;
					
			}
	}
	else
	{
		if($getuserdetail['user_type'] == 4)	
			$_SESSION['msg'] = "<div class='error_msg'><span>This email address already used for tradesman user!</span></div>";
		else
			$_SESSION['msg'] = "<div class='error_msg'><span>This email address already used for sub admin user!</span></div>";
	}

}

$getallTradeCat = $tradeObj->getAllTradesCategoryWithActiveStatus();
$smarty->assign("getallTradeCat", $getallTradeCat);

$getallTradeJobType = $tradeObj->getAllJobTypeWithActiveStatus();
$smarty->assign("getallTradeJobType", $getallTradeJobType);	

/*$tradejobtypeArray = $tradeObj->getAllJobTypeWithActiveStatus();
foreach($tradejobtypeArray as $tradejobtypeArray)
{	
	$newarray[] =	$tradejobtypeArray['parent_id'];
}
	
$tradecategoryArray = array_values(array_unique($newarray));
if($tradecategoryArray[0]!='')
{
		$imopldeids = @implode(",",$tradecategoryArray);
		$newtradecatArray = $tradeObj->getAllTradesCategoryWithmultipleId($imopldeids);
}*/
//echo "<pre>";print_R($getAlltestimonialArray);die();


$newtradecatArray = $tradeObj->getAllTradesCategoryWithmultipleId($getuserdetail['tradeid']);
$smarty->assign("newtradecategoryArray", $newtradecatArray);


$getallactivebudgetArray = $budgetObj->getAllBudgetWithActiveStatus();
$smarty->assign("getallactivebudgetArray", $getallactivebudgetArray);

if($_SESSION['msg']){
		$smarty->assign("msg", $_SESSION['msg']);
		unset($_SESSION['msg']);
}

$active ="findatradesman";
$smarty->assign('active',$active);

$smarty->display(TEMPLATEDIR.'/modules/findtradesman/findtradesmandetail.tpl');
unset($smarty);
?>
